package cn.iocoder.yudao.module.erp.service;

import cn.hutool.core.codec.Base64;
import cn.iocoder.yudao.module.erp.controller.app.auth.vo.CaptchaRespVO;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.module.erp.enums.LoginConstants.CAPTCHA_CODE_KEY;

@Service
@Slf4j
public class AppCaptchaService {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public CaptchaRespVO getCaptcha() throws IOException {
        // 保存验证码信息
        String uuid = UuidUtils.getUUID();
        String verifyKey =CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);

        stringRedisTemplate.opsForValue().set(verifyKey, code, 2, TimeUnit.MINUTES);
        log.info("生成验证码，key: {}, value: {}", verifyKey, code);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            throw new IOException("生成验证码图片失败");
        }
        CaptchaRespVO captchaRespVO = new CaptchaRespVO();
        captchaRespVO.setCaptchaId(uuid);
        captchaRespVO.setImg(Base64.encode(os.toByteArray()));
        return captchaRespVO;
    }


    public boolean validateCaptcha(String captchaId, String code) {
        // 构建验证码的key
        String verifyKey = CAPTCHA_CODE_KEY + captchaId;

        // 从Redis中获取验证码的值
        String correctCode = stringRedisTemplate.opsForValue().get(verifyKey);

        // 如果验证码不存在或已过期，返回false
        if (correctCode == null) {
            return false;
        }

        // 比较用户输入的验证码和正确的验证码
        boolean isValid = correctCode.equalsIgnoreCase(code);

        // 验证码使用一次后删除，防止重复使用
        stringRedisTemplate.delete(verifyKey);

        return isValid;
    }


}
